#include<stdio.h>
#include<pthread.h>

pthread_mutex_t lock;
int tickets = 100;

void init_mutex()
{
    pthread_mutex_init(&lock,NULL);
}

void destory_mutex()
{
    pthread_mutex_destroy(&lock);
}

void*sell_ticket(void*arg)
{
    while(1)
    {
        pthread_mutex_lock(&lock);
        if(tickets>0)
        {
            int ticket = tickets;
            tickets--;
            printf("线程%d卖出一张票，剩余票数：%d\n", pthread_self(), tickets);
        }
        else
        {
            printf("线程%d：票已售完\n", pthread_self());
            break;
        }
        pthread_mutex_unlock(&lock);  // 解锁互斥锁
    }
    return NULL;
}

int main() {
    init_mutex();  // 初始化互斥锁

    pthread_t t1, t2, t3;
    pthread_create(&t1, NULL, sell_ticket, NULL);
    pthread_create(&t2, NULL, sell_ticket, NULL);
    pthread_create(&t3, NULL, sell_ticket, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    destory_mutex();  // 销毁互斥锁
    return 0;
}

